package cn.zeal4j.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @file Spring-Security + Oauth2
 * @create 2020 09 29 11:48
 * @description 授权服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Qualifier("customUserDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Qualifier("getTokenStore")
    @Autowired
    private TokenStore tokenStore;

    @Qualifier("getJwtAccessTokenConverter")
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Qualifier("getJwtTokenEnhancer")
    @Autowired
    private TokenEnhancer tokenEnhancer;

//    @Qualifier("getRedisTokenStore")
//    @Autowired
//    private TokenStore tokenStore;

    /**
     * 使用密码模式需要的配置方法
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        // - - - - - 配置JWT自定义申明增强 Starter - - - - -
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancerList = new ArrayList<>();

        tokenEnhancerList.add(tokenEnhancer);
        tokenEnhancerList.add(jwtAccessTokenConverter);

        tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);
        // - - - - - 配置JWT自定义申明增强 End - - - - -

        endpoints.
                authenticationManager(authenticationManager).
                userDetailsService(userDetailsService).
                accessTokenConverter(jwtAccessTokenConverter).
                tokenEnhancer(tokenEnhancerChain);
//                tokenStore(tokenStore);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.
                inMemory().
                withClient("admin").
                secret(passwordEncoder.encode("112233")).
                // accessTokenValiditySeconds(3600). // 令牌有效时间 一小时
                // redirectUris("http://www.baidu.com"). // 授权成功的跳转
                accessTokenValiditySeconds(3600). // 过期时间
                refreshTokenValiditySeconds(864000).  // 刷新令牌的过期时间
                redirectUris("http://localhost:8081/login").
                autoApprove(true). //自动授权
                scopes("all").  // 所有范围
                // authorizedGrantTypes("authorization_code");     // 授权类型：授权码模式
                authorizedGrantTypes("password", "refresh_token", "authorization_code");     // 授权类型：密码模式 追加令牌刷新，和兼容授权码模式
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 密钥获取之前的身份认证，单点登陆必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }
}
